package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.spell.CombineSuggestion;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shitou
 * @className ApAssociateWordsServiceImpl
 * @description: TODO
 */
@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全功能，关键字联想功能，使用es
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        log.info("自动补全功能，关键字联想功能已执行");
        if (!StringUtils.isNotBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 指定索引库
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        searchRequest.source().suggest(new SuggestBuilder().addSuggestion("keyWordSuggest", SuggestBuilders.completionSuggestion("suggestion").prefix(dto.getSearchWords()).skipDuplicates(true).size(10)));

        // 发送请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        // 解析结果
        Suggest suggest = searchResponse.getSuggest();
        // 根据指定的补全名称，获取补全结果集合
        CompletionSuggestion suggestion = suggest.getSuggestion("keyWordSuggest");
        // 获取命中的options集合
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            list.add(option.getText().toString());
        }
        return ResponseResult.okResult(list);
    }
}
